#include "alttilesetgraphicsitem.h"

#include "alttileset.h"

#include <QGraphicsSceneMouseEvent>
#include <QPainter>

namespace Alt {
     TilesetGraphicsItem::TilesetGraphicsItem(const Tileset* tileset, QGraphicsItem* parent) : QGraphicsItem(parent) {
          setAcceptedMouseButtons(Qt::LeftButton);
          setTileset(tileset);
     }

     QRectF TilesetGraphicsItem::boundingRect() const {
          Q_ASSERT_X(m_tileset != 0, "calculating bounding rect", "null tileset pointer");
          return m_tileset->image().rect();
     }

     void TilesetGraphicsItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* parent) {
          Q_UNUSED(option);
          Q_UNUSED(parent);
          Q_ASSERT_X(m_tileset != 0, "painting", "null tileset pointer");
          painter->drawImage(m_tileset->image().rect(), m_tileset->image());
          return;
     }

     void TilesetGraphicsItem::setTileset(const Tileset* tileset) {
          m_tileset = tileset;
          return;
     }

     const Tileset* TilesetGraphicsItem::tileset() const {
          return m_tileset;
     }

     //public slots
     void TilesetGraphicsItem::update() {
          QGraphicsItem::update(QRectF());
          return;
     }

     //private
     void TilesetGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent* event) {
          event->accept();
          return;
     }

     void TilesetGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) {
          event->accept();
          QPoint pos = event->buttonDownPos(Qt::LeftButton).toPoint();
          Q_ASSERT_X(m_tileset != 0, "tile number calculation", "null tileset pointer");
          pos.rx() /= m_tileset->paddedTileWidth();
          pos.ry() /= m_tileset->paddedTileHeight();
          emit tileClicked(pos.y() * m_tileset->columnCount() + pos.x());
          return;
     }
}
